<template>
  <a-modal
    :title="title"
    :width="500"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 55%;overflow-y: hidden"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务名称">
          <a-input placeholder="请输入任务名称" v-decorator="[ 'modelName', validatorRules.modelName ]"></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="关键字">
          <a-input placeholder="请输入关键字（以逗号分隔）" v-decorator="[ 'keyWord', validatorRules.keyWord ]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="计划开始时间">
          <j-date
            v-model="process.beginTime"
            :showTime="true"
            date-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择计划开始时间"
          ></j-date>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="计划结束时间">
          <j-date
            v-model="process.endTime"
            :showTime="true"
            date-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择计划开始时间"
          ></j-date>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="附件">
          <a-upload
            :action="uploadAction"
            :default-file-list="attachList"
            :headers="headers"
            @change="uploadChanged"
          >
            <a-button>
              <a-icon type="upload" />选择上传文件
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
          <a-textarea :rows="2" v-decorator="[ 'remark', validatorRules.remark ]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="牵头单位">
          <a-cascader
            :options="departmentTree"
            expand-trigger="hover"
            placeholder="请选择部门"
            :display-render="lastDepartment"
            v-decorator="[ 'department', validatorRules.department ]"
          ></a-cascader>
        </a-form-item>
      </a-form>
      <model-deploy-modal ref="deployModal" @deployModel="delopyModel" />
    </a-spin>
  </a-modal>
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import Vue from 'vue'
  import pick from 'lodash.pick'
  import JDate from '@/components/jantd/JDate'
  import { addTaskInfo, allDeployedModel } from '@/api/activiti'
  import { queryDepartTreeList } from '@/api/api'
  import ModelDeployModal from './ActivitiModelDeployModal'

  export default {
    name: 'updateTask',
    components: { JDate, ModelDeployModal },
    data() {
      return {
        title: '操作',
        visible: false,
        roleDisabled: false,
        deployedList: [],
        model: {},
        departmentTree: [],
        attachList: [],
        process: {},
        record:{},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          modelName: {
            rules: [{ required: true, message: '请输入任务名称!' }]
          },
          keyWord: {
            rules: [
              { required: true, message: '请输入关键字!' },
              { min: 2, max: 100, message: '只能输入2-100个字' }
            ]
          },
          beginTime: {
            rules: [{ required: true, message: '请输入计划开始时间!' }]
          },
          endTime: {
            rules: [{ required: true, message: '请输入计划结束时间!' }]
          },
          remark: {
            rules: [
              { required: true, message: '请输入任务描述!' },
              { min: 2, max: 100, message: '只能输入2-100个字' }
            ]
          },
          department: {
            rules: [{ required: true, message: '请选择牵头单位!' }]
          }
        },
        headers: {
          'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)
        }
      }
    },
    created() {
      this.fetchDeployedModel()
      this.fetchDepartmentTree()
    },
    computed: {
      uploadAction() {
        return window._CONFIG['domianURL'] + '/sys/common/upload'
      },
      urlDownload() {
        return window._CONFIG['domianURL'] + '/sys/common/download/'
      }
    },
    methods: {
      add() {
        this.visible = true
        this.form.resetFields()
        // this.$nextTick(() => {
        //   this.$refs.modalSelector.show()
        // })
      },
      fetchDepartmentTree() {
        const vm = this
        queryDepartTreeList().then(res => {
          if (res.success) {
            let array = [].concat(res.result)
            array.forEach(item => {
              vm.toCascader(item)
              item.children &&
              item.children.forEach(c => {
                vm.toCascader(c)
              })
            })
            vm.departmentTree = [].concat(array)
          }
        })
      },
      toCascader(item) {
        item.value = item.title
        item.label = item.title
      },
      lastDepartment({ labels }) {
        return labels[labels.length - 1]
      },
      fetchDeployedModel() {
        const vm = this
        allDeployedModel().then(res => {
          if (res.success) {
            vm.deployedList = [].concat(res.result)
          }
        })
      },
      modelChanged(id) {
        this.model = Object.assign({}, this.deployedList.filter(e => e.id === id)[0])
        this.$refs.deployModal.show(this.model)
      },
      delopyModel(definition) {
        this.process.modelName = definition.name
        this.process.modelKey = definition.key
        this.process.processDefinitionId = definition.id
        this.visible = true
      },
      uploadChanged(info) {
        console.log('--文件列表改变--')
        let fileList = info.fileList
        if (info.file.status === 'done') {
          let array = new Array()
          if (info.file.response.success) {
            fileList = fileList.map(file => {
              if (file.response) {
                file.url = this.urlDownload + file.response.message
                array.push(file.url)
              }
              return file
            })
          }
          this.process.attachments = array.toString()
          this.$message.success(`${info.file.name} 上传成功!`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`)
        } else if (info.file.status === 'removed') {
          console.log(info.file + ' --- removed')
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          console.log(info.file + ' --- path changed')
        }
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let formData = Object.assign(that.process, values)
            formData.department = formData.department[formData.department.length - 1]
            let obj
            console.log(formData)
            if (!this.process.id) {
              obj = addTaskInfo(formData)
            } else {
              obj = addTaskInfo(formData)
            }
            obj
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
                that.close()
              })
          }
        })
      },
      handleCancel() {
        this.close()
      },
      show(record){
        this.visible = true
        this.record = record
      }
    }
  }
</script>

<style scoped>
</style>